package com.wpp.register.metric;

import com.wpp.protocol.RpcRequest;
import org.springframework.util.StopWatch;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Classname ResponseTimeMetricHolder
 * @Description    服务器 响应时间指标 holder
 * @Date 2020/12/8 23:42
 * @Created by wpp25
 */
public class ResponseTimeMetricHolder {

    /**
     * 私有化构造器 不可以 被实例化
     */
    private ResponseTimeMetricHolder() {}

    private static ResponseTimeMetricHolder responseTimeMetricHolder = new ResponseTimeMetricHolder();

    public static ResponseTimeMetricHolder getInstance() {
        return responseTimeMetricHolder;
    }

    public Map<String, TimeMetric> getTimeMetricMap() {
        return timeMetricMap;
    }

    /**
     * key : ip + port
     * value : 请求 耗时
     * 以便  下次 访问服务的时候 取上次 耗时小的服务
     */
    private Map<String,TimeMetric> timeMetricMap = new ConcurrentHashMap<>();

    public void resetResponseTime(RpcRequest request, StopWatch stopWatch) {
        // TODO: 2020/12/8
        timeMetricMap.compute(request.getServerAddress(),(key,value) -> {
            if (value == null) {
                TimeMetric timeMetric = new TimeMetric();
                timeMetric.setLastTimeConsuming(stopWatch.getTotalTimeMillis());
                timeMetric.setLastRequestTime(LocalDateTime.now());
                timeMetric.setClassName(request.getClassName());
                timeMetric.setServerAddress(request.getServerAddress());
                return timeMetric;
            }
            value.setLastTimeConsuming(stopWatch.getTotalTimeMillis());
            value.setLastRequestTime(LocalDateTime.now());
            value.setClassName(request.getClassName());
            value.setServerAddress(request.getServerAddress());

            return value;
        });
    }
}
